package com.dubbo.snail.controller;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import sun.plugin.util.UIUtil;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Description TODO
 * @Author xueguoping
 * @Date 2021/5/10 11:06
 */
@RefreshScope
@RestController
public class ProviderController {

	@Value("${server.port}")
	private String serverPort;

	@GetMapping("/getProvider")
	public String getProvider(){
		return serverPort;
	}

	@HystrixCommand(fallbackMethod = "balanceOpenFeignTimeOut_handler",commandProperties ={
			@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "3000")
	})
	@GetMapping("/getProviderTimeOut")
	public String getProviderTimeOut(){
		try {
			TimeUnit.SECONDS.sleep(3);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		return serverPort;
	}

	public String balanceOpenFeignTimeOut_handler(){
		return Thread.currentThread().getName()+"  balanceOpenFeignTimeOut_handler fallback";
	}



	@HystrixCommand(fallbackMethod = "getProviderbreaker_fallback",commandProperties = {
			@HystrixProperty(name = "circuitBreaker.enabled",value = "true"),// 是否开启断路器
			@HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"),// 请求次数
			@HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000"), // 时间窗口期
			@HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60"),// 失败率达到多少后跳闸
	})
	@GetMapping("/getProviderbreaker/{id}")
	public String getProviderbreaker(@PathVariable("id")int id){
		if(id<0){
			throw new RuntimeException("id 不能小于0");
		}
		return Thread.currentThread().getName()+"getProviderbreaker success "+UUID.randomUUID();
	}

	public String getProviderbreaker_fallback(int id){
		return "id 不能为负数 id:"+id;
	}
}
